import './NewChatPage.css'
import http from '@/utils/axios';
import { memo, useState } from "react";
import useStore from '@/store';
import { useNavigate } from 'react-router-dom';
import ChatTopBar from '@/components/ChatTopBar';
import ChatInputPanel from "@/components/ChatInputPanel";



const NewChat = () => {
    // console.log('NewChat');
    const navigate = useNavigate();
    const newChatPageSelectedModel = useStore(state => state.newChatPageSelectedModel);
    const setNewChatPageSelectedModel = useStore(state => state.setNewChatPageSelectedModel);
    const addDialogue = useStore(state => state.addDialogue);
    const addDialogueHistoryTag = useStore(state => state.addDialogueHistoryTag);
    const setCreatingUUID = useStore(state => state.setCreatingUUID);

    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);

    const handleEnter = async (prompt, setPrompt) => {
        try {
            setIsLoading(true);
            const response = await http.post('/dialogue/', {
                current_model: newChatPageSelectedModel,
                dialogue_content_json: [{
                    role: "user",
                    content: prompt
                }]
            })
            setPrompt('');
            const data = response.data;            
            const dialogueHistoryTag = { uuid: data.uuid, last_modified_time: data.last_modified_time, title: data.title };
            addDialogue(data.uuid, { current_model: data.current_model, dialogue_content_json: data.dialogue_content_json })
            addDialogueHistoryTag(dialogueHistoryTag)
            setCreatingUUID(data.uuid);
            navigate(`/c/${data.uuid}`);
        } catch (error) {
            console.log(error.message);
        } finally {
            setIsLoading(false);
        }
    }

    return (
        <div className="new-chat-page">
            <div style={{ position: 'relative', height: '0' }}><ChatTopBar selectedModel={newChatPageSelectedModel} onSelectedModel={setNewChatPageSelectedModel} /></div>
            <div className='new-chat-page-main'>
                <p style={{ fontSize: '35px', textAlign: 'center' }} >What can I help with?</p>
                <ChatInputPanel onEnter={handleEnter} disabled={isLoading ? true : false} focus={true} />
            </div>
        </div>
    )
};

export default NewChat;